//
//  KWMBaseVC.m
//  IWant_User
//
//  Created by kevin on 12/10/14.
//  Copyright (c) 2014 kollway. All rights reserved.
//

#import "KWMBaseVC.h"
#import "MBProgressHUD.h"
#import "PSPDFAlertView.h"
#import "KWMStringUtil.h"
#import "KWMAPIManager.h"
#import "AppDelegate.h"
//#import "KWMLoginVC.h"
#import "KWMImageUtil.h"
#import "UIColor+SAMAdditions.h"
#import "UIViewController+DismissKeyboard.h"

@implementation KWMBaseVC{
    MBProgressHUD *progressHUD;
    MBProgressHUD *toastHUD;
    int showLoadingCount;
}

+ (NSString *)kwmTag {
    return @"Base";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupForDismissKeyboard];
    [self setNeedsStatusBarAppearanceUpdate];

    [self hideBackTitle];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self
                           selector:@selector(keyboardWillShow:)
                               name:UIKeyboardWillShowNotification
                             object:nil];
    
    [notificationCenter addObserver:self
                           selector:@selector(keyboardWillHide:)
                               name:UIKeyboardWillHideNotification
                             object:nil];
    
    [notificationCenter addObserver:self
                           selector:@selector(doReLogin)
                               name:@"KWMReceiverNoLogin"
                             object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    // unregister for keyboard notifications while not visible.
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter removeObserver:self
                                  name:UIKeyboardWillShowNotification
                                object:nil];
    
    [notificationCenter removeObserver:self
                                  name:UIKeyboardWillHideNotification
                                object:nil];
    
    [notificationCenter removeObserver:self
                                  name:@"KWMReceiverNoLogin"
                                object:nil];
}

-(void)showBackIcon {
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ic_back"] style:UIBarButtonItemStylePlain target:self action:@selector(showLeft)];
}

-(void)showBackIconEmpty {
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
}

-(void)showBackIconWithShadow {
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [backBtn setImage:[UIImage imageNamed:@"ic_back_circle"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(showLeft) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
}

-(void)showLeft {
    [self.navigationController popViewControllerAnimated:YES];
}

//ios8去除tableview separator的左padding
- (void)makeSeparatorZero:(id)currentId {
    if ([currentId respondsToSelector:@selector(setSeparatorInset:)]) {
        [currentId setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([currentId respondsToSelector:@selector(setLayoutMargins:)]) {
        [currentId setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(KWMUserDao *) userDao{
    if(_userDao == nil){
        _userDao = [KWMUserDao shareDao];
    }
    return _userDao;
}


-(KWMSettingDao *) settingDao{
    
    if(_settingDao == nil){
        _settingDao = [KWMSettingDao shareDao];
    }
    return _settingDao;
}


- (KWMAPIManager *)apiManager {
    if (_apiManager == nil) {
        _apiManager = [KWMAPIManager sharedManager];
    }
    return _apiManager;
}

- (AppDelegate *)appDelegate {
    if(_appDelegate == nil){
        _appDelegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
    }
    return _appDelegate;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


- (KWMBaseVC *)findControllerBy:(NSString *)controllerId inStoryboard:(NSString *)storyboardName {
    UIStoryboard *myStoryboard = [UIStoryboard storyboardWithName:storyboardName bundle:nil];
    KWMBaseVC *baseController = [myStoryboard instantiateViewControllerWithIdentifier:controllerId];
    return baseController;
}


- (BOOL)isLoading {
    return showLoadingCount > 0;
}

- (void)keyboardWillHide:(NSNotification *)notification {
    
    if (self.keyboardHeight <= 0) {
        return;
    }
    
    self.keyboardHeight = 0;
}

- (void)keyboardWillShow:(NSNotification *)notification {
    
    if (self.keyboardHeight > 0) {
        return;
    }
    
    self.keyboardHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    
}

- (void)showEmptyView {
    //TODO 显示数据为空的界面
}

- (void)hideEmptyView {
    
}

-(void)showMenuView{
    UIButton *btnMenu = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 40)];
    [btnMenu setImage:[UIImage imageNamed:@"ic_menu"] forState:UIControlStateNormal];
    [btnMenu addTarget:self action:@selector(showLeft:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btnMenu];
}


- (BOOL)hasError:(id)data {
    if (data == nil || [data isKindOfClass:[NSNull class]]) {
        [self showToast:@"返回数据为空"];
        return YES;
    }
    
    NSInteger errorCode = -1;
    NSString *errorMessage = @"未知错误";
    
    if ([data isKindOfClass:[KWMRequestResult class]]) {
        KWMRequestResult *modelData = data;
        errorCode = modelData.code;
        errorMessage = modelData.message;
        
    }else if([data isKindOfClass:[KWMRequestListResult class]]){
        KWMRequestListResult *modelListData = data;
        errorCode = modelListData.code;
        errorMessage = modelListData.message;
        
    }
    
    switch (errorCode) {
        case 0:
            return NO;
        case 1://未登录
            [self.userDao logout];
//            [self toLoginVC];
            return YES;
            
        default:
            [self showToast:errorMessage];
            return YES;
    }
}

- (MBProgressHUD *)showLoading {
    return [self showLoading:self.view cancelable:NO];
}

- (MBProgressHUD *)showLoading:(UIView *)view cancelable:(BOOL)isCancelable {
    if(view == nil){
        return progressHUD;
    }
    
    showLoadingCount++;
    
    if(progressHUD == nil){
        progressHUD = [MBProgressHUD showHUDAddedTo:view animated:YES];
        progressHUD.dimBackground = YES;
        if(isCancelable){
            UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                         action:@selector(hideLoading)];
            [progressHUD addGestureRecognizer:tapGesture];
        }
    }
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSLog(@"showLoading count=%d", showLoadingCount);
    return progressHUD;
}

- (void)hideLoading {
    showLoadingCount--;
    
    if(showLoadingCount <= 0){
        showLoadingCount = 0;
        if(progressHUD != nil){
            [progressHUD hide:YES];
            progressHUD = nil;
        }
    }
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    NSLog(@"hideLoading count=%d", showLoadingCount);
}

- (void)showToast:(NSString *)message {
    
    UIView * contentView = self.navigationController.view != nil ? self.navigationController.view : self.view;
    if(contentView == nil){
        return;
    }
    
    if([KWMStringUtil isBlank:message]){
        return;
    }
    
    if(message.length > 14){
        [self showInfo:message];
    }else{
        if(toastHUD != nil){
            [toastHUD hide:NO];
            toastHUD = nil;
        }
        toastHUD = [MBProgressHUD showHUDAddedTo:contentView animated:YES];
        toastHUD.userInteractionEnabled = NO;
        toastHUD.mode = MBProgressHUDModeText;
        toastHUD.labelText = message;
        toastHUD.removeFromSuperViewOnHide = YES;
        [toastHUD hide:YES afterDelay:2];
    }
}

- (void)showInfo:(NSString *)message {
    [self showInfo:nil message:message];
}

- (void)showInfo:(NSString *)title
         message:(NSString *)message {
    dispatch_after(DISPATCH_TIME_NOW, dispatch_get_main_queue(), ^{
        PSPDFAlertView *alertView = [[PSPDFAlertView alloc] initWithTitle:title message:message];
        [alertView setCancelButtonWithTitle:NSLocalizedString(@"Ok", @"Ok") block:^(NSInteger buttonIndex){
        }];
        [alertView show];
    });
}


- (void)showError:(NSError *)error {
    [self showError:error errorText:NSLocalizedString(@"ErrorData", @"ErrorData")];
}

- (void)showError:(NSError *)error errorText:(NSString *)message {
    //TODO 判断error种类,统一错误提示
    if (error == nil) {
        [self showToast:message];
        return;
    }
    if (error.code == -999) {
        //canceled
        return;
    }
    NSDictionary *userInfo = [error userInfo];
    if (userInfo != nil) {
        NSNumber *errorCodeKey = [userInfo objectForKey:@"_kCFStreamErrorCodeKey"];
        if (errorCodeKey.intValue == 8) {
            [self showToast:@"网络已断开，请重新连接"];
            return;
        }
        NSString *errorMsg = [userInfo objectForKey:@"NSLocalizedDescription"];
        if (![KWMStringUtil isEmpty:errorMsg]) {
            [self showToast:errorMsg];
            return;
        }
    }
    [self showToast:message];
    
}

- (void)hideBackTitle{
    if(self.navigationController.viewControllers.count < 2){
        return;
    }
    UIViewController *vc = (self.navigationController.viewControllers)[self.navigationController.viewControllers.count - 2];
    vc.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)reLoadData {
    NSAssert(NO, @"Not yet Implement Method");
}

- (void)loadData {
    NSAssert(NO, @"Not yet Implement Method");
}


-(BOOL) isBigScreen{
    if(self.view.frame.size.height > 480){
        return YES;
    }else{
        return NO;
    }
}

//- (void)transparentNavigationBar {
//    [UIView animateWithDuration:0.2f animations:^{
//        
//        [self.navigationController.navigationBar setBackgroundImage:[UIImage new]
//                                                      forBarMetrics:UIBarMetricsDefault];
//        self.navigationController.navigationBar.shadowImage = [UIImage new];
//    }];
//    
//}
//
//- (void)unTransparentNavigationBar {
//    [UIView animateWithDuration:0 animations:^{
//        
//        UIImage *image = [KWMImageUtil createColorImage:[UIColor sam_colorWithHex:COLOR_NAV_BAR]];
//        [self.navigationController.navigationBar setBackgroundImage:image
//                                                      forBarMetrics:UIBarMetricsDefault];
//        self.navigationController.navigationBar.shadowImage = [UIImage new];
//    }];
//}

#pragma mark LoginDelegate
-(void)kwm_loginSuccess{
    
}

-(void)kwm_loginFail{
    
}

-(void)doReLogin{
    //    [[KWMUserDao shareDao] logoutUser];
    //    [self performSelector:@selector(popToPerviousController) withObject:nil afterDelay:0.5];
}
//
//// 去往登录界面
//- (void)toLoginVC {
//    KWMLoginVC *loginVC = (KWMLoginVC *)[self findControllerBy:[KWMLoginVC kwmTag] inStoryboard:@"Main"];
//    [self.navigationController pushViewController:loginVC animated:YES];
//}

@end
